#include <iostream>
#include <sys/socket.h> // socket
#include <netinet/in.h> // local
#include <arpa/inet.h> // htons inet_addr
#include <cstring> // memset 
#include <unistd.h> // close

// ./TestUDPServer port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Please Use:./TestUDPServer port" << std::endl;
        return 1;
    }

    uint16_t serverport = std::stoi(argv[1]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socket fail" << std::endl;
        exit(1);
    }

    sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = INADDR_ANY; // 绑定到本机的任意地址

    int n = bind(sockfd, (struct sockaddr*)&server, sizeof(server));
    if (n < 0)
    {
        std::cout << "bind fail" << std::endl;
        close(sockfd);
        return 1;
    }

    std::cout << "UDP Server is running..." << std::endl;

    while (true)
    {
        char buffer[1024];
        sockaddr_in client;
        socklen_t len = sizeof(client); // 需要初始化
        memset(&client, 0, sizeof(client));
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&client, &len);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say# " << buffer <<std::endl; 
            ssize_t m = sendto(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&client, len);
            if (m < 0) 
            {
                std::cout << "sendto fail" << std::endl;
                break;
            }
        }
        else
        {
            std::cout << "recvfrom fail" << std::endl;
            break;
        }
    }

    close(sockfd);

    return 0;
}